// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database();
const _ = db.command;
const $ = db.command.aggregate;

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  let limit_num = event.limit;
  let skip_num = event.skip;
  console.log('limit_num:'+limit_num+';skip_num:'+skip_num);
  let openid = wxContext.OPENID;
  let card_status = event.card_status;
  let order_status = event.order_status;
  let res = new Object();
  let card_ids = await db.collection('ops_card').where({
    Issuer_openid: openid,
    status: card_status
  }).field({
    _id: true
  }).get();
  let id_array = [];
  for(i=0;i<card_ids.data.length;i++){
    id_array[i] = card_ids.data[i]._id;
  }
  let order_list = await db.collection('ops_order').aggregate().sort({
    update_time: -1
  }).match({
    card_id: _.in(id_array),
    status: order_status
  }).project({
    goods_id: 1,
    goods_number: 1,
    user_address: 1,
    user_name: 1,
    user_phone_number: 1,
    user_delivery_date: 1,
    express_number: 1,
    card_id: 1,
    update_time_show: $.dateToString({
      date: '$update_time',
      format: '%Y-%m-%d %H:%M:%S',
      timezone: 'Asia/Shanghai'
    })
  }).lookup({
    from: 'ops_goods',
    localField: 'goods_id',
    foreignField: '_id',
    as: 'goodsList',
  }).replaceRoot({
    newRoot: $.mergeObjects([$.arrayElemAt(['$goodsList', 0]), '$$ROOT'])
  }).project({
    goodsList: 0,
    Issuer_openid: 0,
    goods_explain: 0,
    goods_id: 0,
    goods_url: 0
  }).limit(limit_num).skip(skip_num).end();
  res.length = id_array.length;
  res.list = order_list.list;
  return res;
}